<template>
  <div class="approve-msg__list">
    <div class="approve-msg__list__tabs">
      <div>
        <div
          v-for="item in messageType"
          :key="item.value"
          @click="changeMessageType(item.value)"
          class="tabs-item"
          :class="{ 'tabs-item--active': messageTypeTab === item.value }"
        >
          {{ item.label }}
        </div>
      </div>
      <div class="check-more" @click="handelCheckMore">
        <span class="check-more__label">查看更多</span>
        <icon-double-right :style="{ color: '#007DFF' }" />
      </div>
    </div>
    <div class="approve-msg__items">
      <a-spin :loading="isLoading">
        <template v-if="messageList.length">
          <div v-for="item in messageList" :key="item.dataId" class="msg-item" @click="showConfirmDrawer(item)">
            <div class="msg-item__title">
              <span class="msg-item__title__label">
                <span>【{{ msgTag(item.msgType).value }}】</span>
                {{ item.title }}
              </span>
              <span class="status-tag status-tag--warning" v-show="isTreated(item).value">待确认</span>
            </div>
            <div class="msg-item__user">
              <span class="msg-item__user__label">发起人：{{ item.user }} | {{ item.createTime }}</span>
              <span class="msg-item__user__tip" v-show="autoTreated(item).value.isShow">{{ autoTreated(item).value.label }}</span>
            </div>
          </div>
        </template>
        <a-empty v-else description="这里暂时什么都没有哦~">
          <template #image>
            <img :src="homeAuditIcon" alt="" />
          </template>
        </a-empty>
      </a-spin>
    </div>
  </div>

  <!-- 消息确认 start -->
  <div class="message-drawer">
    <a-drawer
      :visible="isShowMessageConfirm"
      :footer="false"
      :width="480"
      title-align="start"
      :header="false"
      unmountOnClose
      :mask-closable="false"
      :render-to-body="false"
    >
      <a-spin :loading="messageDetailLoading" tip="数据加载中...">
        <div class="msg-body">
          <div class="msg-body__title">
            <custom-title title="消息确认" />
            <IconClose style="cursor: pointer" @click="handleDrawerCancel(false)" />
          </div>
          <div class="msg-body__content">
            <div class="message-promoter">
              <span class="user-name">发起人-{{ messageDetail.sendName }}</span>
              <span class="confirm-status" v-if="autoTreated(messageDetail).value.isShow"
                >{{ autoTreated(messageDetail).value.label }}天后自动确认</span
              >
              <!--        确认状态标识 start    -->
              <div class="confirm-status--read" v-if="isNormalMsg">已阅读</div>
              <template v-else>
                <GiSvgIcon
                  class="confirm-status--refuse"
                  name="refuse"
                  size="62"
                  v-if="messageDetail.status == msgStatusValue.refused"
                ></GiSvgIcon>
                <GiSvgIcon
                  class="confirm-status--confirm"
                  name="confirm"
                  size="62"
                  v-if="messageDetail.status == msgStatusValue.confirmed"
                ></GiSvgIcon>
              </template>
              <!--         确认状态标识 end   -->
            </div>

            <!--       消息详情 start   -->
            <message-detail-form :form-data="formData(messageDetail.msgContent).value" />
            <!--        消息详情 end  -->

            <!--      附件上传 start    -->
            <div class="confirm-file" v-if="!isNormalMsg">
              <div class="confirm-file__upload" v-if="isAwaitComfirmMsg">
                <div class="confirm-file__button">
                  <a-upload
                    multiple
                    :show-file-list="false"
                    :show-preview-button="false"
                    :custom-request="customUpload as any"
                    :on-before-upload="handelBeforeUpload as any"
                  >
                    <template #upload-button>
                      <GiSvgIcon name="up-icon" size="20" />
                      <span class="upload-button">上传附件</span>
                    </template>
                  </a-upload>
                </div>
                <div class="confirm-file__tip">支持上传rar/zip/doc/docx/xls/xlsx/pdf/jpg/png，单个文件不超过200M</div>
              </div>
              <!--      拒绝理由 start-->
              <div class="refused-reason" v-if="messageDetail.status === msgStatusValue.refused">
                <div class="refused-reason__label">拒绝理由</div>
                <div class="refused-reason__content">
                  {{ messageDetail.msgDescription }}
                </div>
              </div>
              <!--      拒绝理由 end-->
              <message-file-list v-model="confirmFileList" :is-options="isAwaitComfirmMsg" />
            </div>
            <!--       附件上传 end   -->
          </div>
        </div>
        <div class="buttons" v-if="isAwaitComfirmMsg">
          <a-button class="cancel-button" type="secondary" @click="handelShowRefuseMsg" :disabled="isHandleMsgLoading"
            >拒绝</a-button
          >
          <a-button class="confirm-button" type="primary" :loading="isHandleMsgLoading" @click="handelConfirmMsg">确认</a-button>
        </div>
      </a-spin>
    </a-drawer>
  </div>
  <!-- 消息确认 end -->

  <!-- 拒绝理由弹窗 start-->
  <refuse-model v-model="isShowRefuseModel" :msg-id="msgId" :file-list="confirmFileList" @cancel="handelCancelRefuseModel" />
  <!--  拒绝 end-->
</template>

<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import MessageFileList from "./components/MessageFileList/index.vue";
import MessageDetailForm from "./components/messageDetailForm/index.vue";
import refuseModel from "./components/refuseModel/index.vue";
import { messageType, msgTypes, msgStatusValue } from "@/views/home/config";
import defaultConfig from "@/config/settings";
import { parseOrDefault } from "@/utils";
import { getCurrentTime, getRandom, getFileName, getSuffix } from "@/utils/oss";
import useMultipartOssStore from "@/stores/modules/multipartOssStore";
import useComputedParams from "@/hooks/useComputedParams";
import { workbenchMsgList, workbenchMsgDetail, workbenchMsgHandle } from "@/apis";
import type { WorkbenchMsgListParams, MsgDetail, AttachmentsListItem, MsgConfirmParams } from "@/apis";
import homeAuditIcon from "@/assets/images/home-audit-icon.png";

const props = defineProps({
  filterTab: String,
  auditMsgStatus: String
});
const emit = defineEmits(["changeFilterTab", "drawerMsgCancel"]);
const router = useRouter();
const ossStore = useMultipartOssStore();

/**
 * 是否普通消息
 */
const isNormalMsg = computed(() => {
  return messageDetail.value.noticeType === 1;
});
/**
 *  是否待确认消息
 *  我接收 + 待确认消息 + 待处理消息 才可以操作
 *  noticeType 1--普通消息 2--查看可确认 3--查看可确认拒绝
 *  status 1--未查看，2--已查看待确认，3--已确认，4--已同意，5--已拒绝，6--已撤回
 */
const isAwaitComfirmMsg = computed(() => {
  return props.filterTab === "msgAccept" && !isNormalMsg.value && messageDetail.value.status === 2;
});

// 处理  默认我收到的
const messageTypeTab = ref<string>("msgAccept");
// 消息类型切换
const changeMessageType = (tabType: string) => {
  messageTypeTab.value = tabType;
  emit("changeFilterTab", tabType);
};
/**
 * 消息类型
 */
const msgTag = useComputedParams(data => {
  return msgTypes.has(data) ? msgTypes.get(data) : "其他";
});
/**
 * 是否确认
 */
const isTreated = useComputedParams(data => {
  return messageTypeTab.value === "msgAccept" && props.auditMsgStatus === "untreated" && data.noticeType !== 1;
});
/**
 * 是否配置自动确认
 * 工作台消息配置自动确认，根据左边筛选按钮盘算
 */
const autoTreated = useComputedParams(data => {
  if (!isTreated.value) {
    return { isShow: false, label: "" };
  }
  if (data.autoTreated > 0) {
    return { isShow: true, label: `${data.autoTreated}天后自动确认` };
  }
  if (data.autoTreated === 0) {
    return { isShow: true, label: "当天自动确认" };
  }
  return { isShow: false, label: "" };
});
/**
 * 消息列表
 */
const isLoading = ref(false);
const messageList = ref<any>([]);
const getWorkbenchMsgList = async (params: WorkbenchMsgListParams) => {
  try {
    isLoading.value = true;
    const { data } = await workbenchMsgList(params);
    messageList.value = data?.list ?? [];
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};

/**
 * 上传附件
 */
const confirmFileList = ref<AttachmentsListItem[]>([]);
const fileTypes = ["rar", "zip", "doc", "docx", "xls", "xlsx", "pdf", "jpg", "png"];
const customUpload = async (option: any) => {
  let file = option.fileItem;
  const fileId = file.uid;
  let fileName = `${getFileName(file.name)}-${getCurrentTime()}${getRandom()}.${getSuffix(file.name)}`;
  file = new File([file], fileName, { type: file.type });
  let objName = `${defaultConfig.fileFolder}/${fileName}`;
  ossStore
    .submit(objName, option.fileItem.file, fileId)
    .then(async () => {
      await ossStore.setACL(objName, defaultConfig.fileReadRole.publicRead);
      const fileUrl = await ossStore.signatureUrl(objName);
      const url = fileUrl ? `${fileUrl}`.split("?")[0] : "";
      const fileObj: AttachmentsListItem = {
        msgId: msgId.value,
        url,
        fileName
      };
      // res.fileUrl = await ossStore.signatureUrl(objName);
      // res.url = res.fileUrl ? `${res.fileUrl}`.split("?")[0] : "";
      // res.fileId = option.fileItem.uid;
      // res.uid = option.fileItem.uid;
      // res.size = file.size;
      // res.file = option.fileItem.file;
      // res.fileName = option.fileItem.name;
      // res.name = option.fileItem.name;
      // res.file.suffix = getSuffix(option.fileItem.name);
      confirmFileList.value.push(fileObj);
    })
    .catch((err: any) => {
      console.log(err);
    });
};
const handelBeforeUpload = (file: File) => {
  const maxSize = file?.size / 1024 / 1024 < 200;
  const suffix = getSuffix(file.name);
  if (!maxSize) {
    Message.error("单个文件大小不能超过200M!");
    return false;
  }
  if (!fileTypes.includes(suffix)) {
    Message.error(`请上传${fileTypes.join("/")}文件!`);
    return false;
  }
  return true;
};

/**
 * 确认消息
 * @param item
 */
const messageDetailLoading = ref(false);
const msgId = ref("");
const messageDetail = ref<MsgDetail>({} as MsgDetail);
// 表单详情
const isShowMessageConfirm = ref(false);
const formData = useComputedParams(data => {
  return parseOrDefault(data, []);
});
const getWorkbenchMsgDetail = async (msgId: string) => {
  try {
    messageDetailLoading.value = true;
    const { data } = await workbenchMsgDetail(msgId);
    messageDetail.value = data ?? {};
    confirmFileList.value = data?.attachmentsList ?? [];
    messageDetailLoading.value = false;
  } catch (err) {
    messageDetailLoading.value = false;
    console.log(err);
  }
};
// 处理消息
const isHandleMsgLoading = ref(false);
const showConfirmDrawer = (item: any) => {
  msgId.value = item.dataId;
  isShowMessageConfirm.value = true;
  getWorkbenchMsgDetail(item.dataId);
};
//确认
const handelConfirmMsg = async () => {
  try {
    isHandleMsgLoading.value = true;
    const postData: MsgConfirmParams = {
      msgId: msgId.value,
      status: 4,
      opinionInfo: "",
      resourceUrls: confirmFileList.value
    };
    await workbenchMsgHandle(postData);
    Message.success("操作成功");
    isHandleMsgLoading.value = false;
    handleDrawerCancel(true);
  } catch (err) {
    isHandleMsgLoading.value = false;
  }
};
// 拒绝
const isShowRefuseModel = ref(false);
const handelShowRefuseMsg = () => {
  isShowRefuseModel.value = true;
};
const handelCancelRefuseModel = (isRefresh: boolean) => {
  isShowRefuseModel.value = false;
  isRefresh && handleDrawerCancel(isRefresh);
};

// 关闭
const handleDrawerCancel = (isRefresh: boolean) => {
  isShowMessageConfirm.value = false;
  emit("drawerMsgCancel", isRefresh);
};

const handelCheckMore = () => {
  router.push("/message-list");
};

defineExpose({
  getWorkbenchMsgList
});
</script>

<style scoped lang="scss">
@import "messageList";
:deep(.arco-spin) {
  @include flex-column;
  width: 100%;
  height: 100%;
}
</style>
